//
//  HomeViewController.swift
//  Weibo
//
//  Created by 孙国强 on 2017/6/18.
//  Copyright © 2017年 孙国强. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeViewController: BaseViewController {

    // MARK:- 属性
    var isPresented: Bool = false
    
    // MARK:- 懒加载属性
    lazy var titleBtn : TitleButton = TitleButton()
    lazy var popoverAnimator : PopoverAnimator = PopoverAnimator {[weak self] (presented) in
        self?.titleBtn.isSelected = presented
    }
    
    fileprivate lazy var statusViewModels : [StatusViewModel] = [StatusViewModel]()
    fileprivate lazy var tipLabel : UILabel = UILabel()
    fileprivate lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
    
    // MARK:- 系统回调方法
    override func viewDidLoad() {
        super.viewDidLoad()

        // 没有登录时设置的内容
        visitorView.addRotationAnim()
        if !isLogin {
            return
        }
        
        // 设置导航栏的内容
        setupNavigationBar()
        
        // 设置估算高度
        tableView.estimatedRowHeight = 200
        
        // 布局header
        setupHeaderView()
        setupFooterView()
        
        // 设置提示的Label
        setupTipLabel()
        
        // 监听通知
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.showPhotoBrowser(note:)), name: NSNotification.Name(ShowPhotoBrowserNote), object: nil)
    }
}

// MARK:- 设置UI界面
extension HomeViewController {
    fileprivate func setupNavigationBar() {
        // 设置左侧Item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        
        // 设置右侧Item
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        // 设置标题栏
        titleBtn.setTitle("John", for: .normal)
        titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(titleBtn:)), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    fileprivate func setupHeaderView() {
        // 创建headerView
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewStatuses))
        
        // 设置Header的属性
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("释放更新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        
        // 设置tableView的Header
        tableView.mj_header = header
        
        // 进入刷新状态
        tableView.mj_header.beginRefreshing()
    }
    
    fileprivate func setupFooterView() {
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreStatuses))
    }
    
    fileprivate func setupTipLabel() {
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        
        tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32)
        
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: 14)
        tipLabel.textAlignment = .center
        tipLabel.isHidden = true
    }
}

// MARK:- 事件监听
extension HomeViewController {
    @objc fileprivate func titleBtnClick(titleBtn : TitleButton) {
        titleBtn.isSelected = !titleBtn.isSelected
        
        let popoverVC = PopoverViewController()
        
        // 设置控制器的modal样式(custom：弹出控制器后，不移除原本显示的控制器)
        popoverVC.modalPresentationStyle = .custom
        
        // 设置转场的代理
        popoverVC.transitioningDelegate = popoverAnimator
        popoverAnimator.presentedViewFrame = CGRect(x: 100, y: 55, width: 180, height: 250)
        
        present(popoverVC, animated: true, completion: nil)
    }
    
    @objc fileprivate func showPhotoBrowser(note : Notification) {
        let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! NSIndexPath
        let picURLs = note.userInfo![ShowPhotoBrowserURLsKey] as! [URL]
        let object = note.object as! PicCollectionView
        
        let photoBrowserVC = PhotoBrowserController(indexPath: indexPath, picURLs: picURLs)
        
        photoBrowserVC.modalPresentationStyle = .custom
        
        // 设置转场的代理
        photoBrowserVC.transitioningDelegate = photoBrowserAnimator
        
        // 设置动画的代理
        photoBrowserAnimator.presentedDelegate = object
        photoBrowserAnimator.indexPath = indexPath
        photoBrowserAnimator.dismissDelegate = photoBrowserVC
        
        present(photoBrowserVC, animated: true, completion: nil)
    }
}

// MARK:- 请求数据
extension HomeViewController {
    // 下拉加载最新的数据
    @objc fileprivate func loadNewStatuses() {
        loadStatuses(isNewData: true)
    }
    
    // 上拉加载更多数据
    @objc fileprivate func loadMoreStatuses() {
        loadStatuses(isNewData: false)
    }
    
    // 加载微博数据
    fileprivate func loadStatuses(isNewData : Bool) {
        
        // 获取since_id
        var since_id = 0
        var max_id = 0
        if isNewData {
            since_id = statusViewModels.first?.stauts?.mid ?? 0
        } else {
            max_id = statusViewModels.last?.stauts?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        
        // 请求数据
        NetworkTools.shareInstance.loadStatuses(since_id: since_id, max_id: max_id) { (result, error) in
            // 错误校验
            if error != nil {
                print(error!)
                return
            }
            
            // 获取可选类型中的数据
            guard let resultArray = result else {
                return
            }
            
            // 遍历微博对应的字典
            var tempViewModels = [StatusViewModel]()
            for statusDict in resultArray {
                let status = Status(dict: statusDict)
                let viewModel = StatusViewModel(status: status)
                tempViewModels.append(viewModel)
            }
            
            // 将数据放入到成员变量的数组中
            if isNewData {
                self.statusViewModels = tempViewModels + self.statusViewModels
            } else {
                self.statusViewModels += tempViewModels
            }
            
            // 缓存图片
            self.cacheImages(viewModels: tempViewModels)
        }
    }
    
    private func cacheImages(viewModels : [StatusViewModel]) {
        // 创建group
        let group = DispatchGroup()
        
        // 缓存图片
        for viewModel in viewModels {
            for var picURL in viewModel.picURLs {
                group.enter()
                SDWebImageManager.shared().loadImage(with: picURL, options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                    group.leave()
                })
            }
        }
        
        // 刷新表格
        group.notify(queue: DispatchQueue.main) { 
            self.tableView.reloadData()
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            // 显示提示的Label
            self.showTipLabel(count: viewModels.count)
        }
    }
    
    private func showTipLabel(count : Int) {
        tipLabel.isHidden = false
        tipLabel.text = count == 0 ? "没有新数据" : "\(count) 条新微博"
        
        UIView.animate(withDuration: 1.0, animations: { 
            self.tipLabel.frame.origin.y = 44
        }) { (_) in
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: { 
                self.tipLabel.frame.origin.y = 10
            }, completion: { (_) in
                self.tipLabel.isHidden = true
            })
        }
    }
}

// MARK:- 数据源方法
extension HomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusViewModels.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeViewCell
        
        cell.viewModel = self.statusViewModels[indexPath.row]
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return statusViewModels[indexPath.item].cellHeight
    }
}
